import { ElLoading } from 'element-plus'
import { ref, watch, unref, onMounted, Ref } from 'vue'

export const useTable = (fetchDataApi: () => Promise<{ list: any[], total?: number, stats: Record<string, any> }>, target?: Ref, immediate = true) => {
  const loading = ref(false)
  const currentPage = ref(1)
  const pageSize = ref(20)
  const total = ref(0)
  const dataList = ref<any[]>([])
  const stats = ref<Record<string, any>>({})
  let loadingInstance

  onMounted(() => {
    if (immediate) refresh()
  })

  const refresh = async () => {
    loading.value = true
    if(target?.value) loadingInstance = ElLoading.service({ target: target.value })
    try {
      const res = await fetchDataApi()
      if (res) {
        dataList.value = res.list
        total.value = res.total || 0
        stats.value = res.stats
      }
    } catch (err) {
      console.log('fetchDataApi error')
    } finally {
      loading.value = false
      loadingInstance?.close()
    }
  }

  watch(() => currentPage.value, () => refresh())

  watch(
    () => pageSize.value,
    () => {
      // 当前页不为1时，修改页数后会导致多次调用refresh方法
      if (unref(currentPage) === 1) {
        refresh()
      } else {
        currentPage.value = 1
        refresh()
      }
    }
  )

  return {
    refresh,
    currentPage,
    pageSize,
    total,
    dataList,
    stats,
    loading
  }
}
